package com.git.contractmanagement.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileService {

    @Value("${file.upload-dir}")
    private String uploadPath;

    /**
     * 保存上传的文件并返回相对路径
     */
    public String saveFile(MultipartFile file, String targetDir) throws IOException {
        File dir = new File(uploadPath + "/" + targetDir);
        if (!dir.exists()) dir.mkdirs();

        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        Path filePath = Paths.get(dir.getAbsolutePath(), fileName);

        try (InputStream is = file.getInputStream();
             OutputStream os = new FileOutputStream(filePath.toFile())) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }
        return targetDir + "/" + fileName;
    }

    /**
     * 读取文件为字节数组
     */
    public byte[] readFileAsBytes(String relativePath) throws IOException {
        Path path = Paths.get(uploadPath, relativePath);
        return Files.readAllBytes(path);
    }

    /**
     * 删除文件
     */
    public boolean deleteFile(String relativePath) {
        Path path = Paths.get(uploadPath, relativePath);
        try {
            return Files.deleteIfExists(path);
        } catch (IOException e) {
            return false;
        }
    }
    public String getUploadPath() {
        return uploadPath;
    }
}